import java.net.*;
import java.io.*;

public class UDPServer {

    public static void main(String args[]) {
        try {
            DatagramSocket aSocket = new DatagramSocket(6789);
       
            BufferedWriter writer = new BufferedWriter(new FileWriter("socketCmd"));
            
            while (true) {

		byte[] buffer = new byte[20];

		DatagramPacket request = new DatagramPacket(buffer, buffer.length);
                aSocket.receive(request);
                String msgRec = new String(request.getData());

                // tamanho padrao de mensagem: <1234567i>; i=identificador
                //msgRec = msgRec.substring(0, 10);

                System.out.println("recebi: " + msgRec);

                writer.write(msgRec);
                writer.newLine();
                writer.flush();

                DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(), request.getAddress(), request.getPort());
                aSocket.send(reply);
            }
            //writer.close();


        } catch (SocketException e) {
            System.out.println("Socket:" + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO:" + e.getMessage());
        }
        //finally {    writer.close();         }
    }
}